/
MemoryStorage.php
68 lines (54 loc) 路 1.53 KB
/
MemoryStorage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
declare(strict_types=1);
namespace Aeon\RateLimiter\Storage;
use Aeon\Calendar\Gregorian\Calendar;
use Aeon\Calendar\TimeUnit;
use Aeon\RateLimiter\Hit;
use Aeon\RateLimiter\Hits;
use Aeon\RateLimiter\Storage;
final class MemoryStorage implements Storage
{
use StorageIdNormalizer;
private Calendar $calendar;
/**
* @var array<string, Hits>
*/
private array $hits;
public function __construct(Calendar $calendar)
{
$this->calendar = $calendar;
$this->hits = [];
}
public function addHit(string $id, TimeUnit $ttl) : void
{
if (!$this->hasFor($id)) {
$this->hits[$this->normalize($id)] = new Hits(new Hit($id, $this->calendar->now(), $ttl));
} else {
$this->hits[$this->normalize($id)] = $this->hits($this->normalize($id))
->add(new Hit($id, $this->calendar->now(), $ttl))
->filterExpired($this->calendar);
}
}
public function all(string $id) : Hits
{
return $this->hits($id);
}
public function count(string $id) : int
{
return $this->hits($id)->count();
}
private function hits(string $id) : Hits
{
if (!$this->hasFor($id)) {
return new Hits();
}
return $this->hits[$this->normalize($id)]->filterExpired($this->calendar);
}
private function hasFor(string $id) : bool
{
if (!\array_key_exists($this->normalize($id), $this->hits)) {
return false;
}
return true;
}
}